/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package asteroidmining1;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JFrame;

/**
 *
 * @author IVAN
 */
public class frmPrincipal extends javax.swing.JFrame
        implements Runnable {

    boolean up = false, down = false, tiro = false, lancar = false, sair = false, gravityForce = false;
    double power;
//    frame.setSize(xSize,ySize);  
    private static final int FRAME_WIDTH = ((int) Toolkit.getDefaultToolkit().getScreenSize().getWidth());
    private static final int FRAME_HEIGHT = ((int) Toolkit.getDefaultToolkit().getScreenSize().getHeight());
    private int angle;
    private String message;
    private CannonBall cannonBall;
    private Collision collision;
    private ArrayList<Asteroid> _asteroids;
    double radianAngle;
    double sinAngle;
    double cosAngle;

    /**
     * Creates new form frmPrincipal
     */
    public frmPrincipal(int theta) {
        super();


        //Iniciando a Thread que roda o jogo                                        


        initComponents();

        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        setTitle("Asteroid mining Game");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        angle = theta;
        message = "Angle = " + angle;
        radianAngle = angle * Math.PI / 180.0;
        sinAngle = Math.sin(radianAngle);
        cosAngle = Math.cos(radianAngle);

        Thread t = new Thread(this);
        createBufferStrategy(2);
        t.start();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                formKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1024, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 768, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_UP) {
            up = true;
        }

        if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
            down = true;
        }

        if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
            tiro = true;
        }

        if (evt.getKeyCode() == KeyEvent.VK_F7) {
            sair = true;
        }
    }//GEN-LAST:event_formKeyPressed

    private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_UP) {
            up = false;
        }

        if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
            down = false;
        }

        if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
            tiro = false;
            lancar = true;
        }
    }//GEN-LAST:event_formKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {


        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmPrincipal(Integer.parseInt("45")).setVisible(true);
//                frmPrincipal world = new frmPrincipal(Integer.parseInt("45"));
//                world.setVisible(true);
//                world.run();

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {
        boolean exit = false;
        do {


            sair = false;
            cannonBall = null;

            _asteroids = new ArrayList<>();

            Asteroid a = new Asteroid(600, 400, 100, 3);
            _asteroids.add(a);

             
            
            
            while (cannonBall == null) {

                Graphics g = getBufferStrategy().getDrawGraphics();
                
                g.setColor(Color.DARK_GRAY);
        g.fillRect(0,0, getWidth(), getHeight());
                
                drawCannon(g);
        //        drawTarget(g);
                drawCannonball(g);
                drawMessage(g);

                drawAsteroids(g);
                drawPowerBar(g);
                
                
                
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                }

                message = "Angle = " + angle;
                radianAngle = angle * Math.PI / 180.0;
                sinAngle = Math.sin(radianAngle);
                cosAngle = Math.cos(radianAngle);

                if (up) {
                    if (angle < 90) {
                        angle += 1;
                    }
                } else if (down) {
                    if (angle > -90) {
                        angle -= 1;
                    }
                }
                if (tiro) {
                    if (power <= 100) {
                        if (power <= 30) {
                            power += 0.5;
                        }
                        if (power <= 70) {
                            power += 1;
                        }
                        if (power > 70) {
                            power += 2;
                        }

                    }

                }

                if (lancar) {
                    cannonBall = new CannonBall(20 + (int) (cosAngle),
                            //                dy(5 + (int) (power * sinAngle)),
                            dy(200 + (int) (sinAngle)),
                            5, (12 + (power / 50)) * cosAngle, -1 * (12 + (power / 50)) * sinAngle);
//                cannonBall = new CannonBall(20 + (int) (30 * cosAngle),                
//                dy(5 + (int) (30 * sinAngle)),
//                5, 12 * cosAngle, -12 * sinAngle);                        
                }
               // repaint();
                
               g.dispose();
               getBufferStrategy().show();
                
            }

            while (cannonBall != null) {
                    Graphics g = getBufferStrategy().getDrawGraphics();
                    
                    g.setColor(Color.DARK_GRAY);
        g.fillRect(0,0, getWidth(), getHeight());
        
                    drawCannon(g);
        //        drawTarget(g);
                drawCannonball(g);
                drawMessage(g);

                drawAsteroids(g);
                drawPowerBar(g);

                if (collision == null) {
                    collision = new Collision();
                    collision.setHeight(FRAME_WIDTH);
                    collision.setWidth(FRAME_WIDTH);
                }

                //Acelera o movimento da bola
                try {
                    Thread.sleep((long) (30));
                } catch (InterruptedException e) {
                }

                //Colisao entre Tiro e Raio Gravitacional
                if (collision.CollisionBetweenBallAndAtmosfere(cannonBall, a)) {
                    gravityForce = true;
                    //Encontrar velocidade máxima (escape)
//                    cannonBall.setMaxvy( Math.abs( cannonBall.xMotion()*50000000));
//                    cannonBall.setMaxvy( Math.abs( cannonBall.xMotion()*50000000));                    
                    cannonBall.setMaxvx(23);
                    cannonBall.setMaxvy(23);

                }

                if (gravityForce) {
                    collision.EnterInGravityField(cannonBall, a);
                    collision.GravityPower(cannonBall, a);
                }

                //Colisao entre Tiro e Asteroid
                if (collision.CollisionBetweenBallAndAsteroid(cannonBall, a)) {

                    //TODO1: Verificar se houve colisao com o alvo
                    //TODO2: verificar se é alvo final
                    cannonBall.setMotion(0, 0);
                    cannonBall = null;
                }

                //Saiu do cenario                
                if (collision.BallOutOfCenario(cannonBall)) {
                    cannonBall = null;
                }
             g.dispose();
               getBufferStrategy().show();
                        
            }


            sair = false;

            tiro = false;
            lancar = false;
            power = 0;
            gravityForce = false;
            //repaint();

            try {
                Thread.sleep((long) (30));
            } catch (InterruptedException e) {
            }

        } while (!sair);

        this.setVisible(false);
    }
    
    public void paint(Graphics g) {
        super.paint(g);

    }

    protected void drawCannon(Graphics g) {
        int x = 20;
//        int y = 5;
        int y = 200;
        double radianAngle = angle * Math.PI / 180.0;
        int lv = (int) (30 * Math.sin(radianAngle));
        int lh = (int) (30 * Math.cos(radianAngle));
        int sv = (int) (10 * Math.sin(radianAngle + Math.PI / 2));
        int sh = (int) (10 * Math.cos(radianAngle + Math.PI / 2));
        g.setColor(Color.green);
        g.drawLine(x, dy(y), x + lh, dy(y + lv));
        g.drawLine(x + lh, dy(y + lv), x + lh + sh, dy(y + lv + sv));

        //Mira
        //TODO: Colocar linha da mira
//        g.drawLine(x + lh + sh, dy(y + lv + sv/2), x +50+ sh, dy(y + sv + 50) );

        g.drawLine(x + lh + sh, dy(y + lv + sv), x + sh, dy(y + sv));
        g.drawLine(x + sh, dy(y + sv), x, dy(y));
        g.drawOval(x - 8, dy(y + 10), 12, 12);
    }

    protected void drawPowerBar(Graphics g) {
        int x = 20;
        int y = 50;

        g.setColor(Color.red);
        g.drawRect(x, y, 100, 30);
        if (tiro || lancar) {
            g.fillRect(x, y, (int) power, 30);
        }
    }

    protected void drawAsteroids(Graphics g) {
        for (Asteroid a : _asteroids) {
            a.paint(g);
        }
    }

    protected void drawCannonball(Graphics g) {
        if (cannonBall != null) {
            cannonBall.move();
            cannonBall.paint(g);
        }
    }

    protected void drawMessage(Graphics g) {

        int x = 200;
        int y = 50;

        g.drawString(message, x, y);
    }

    public static int dy(int y) {
        return FRAME_HEIGHT - y;
    }
}